package controller

import (
	"elegantGo/chapter17/controller/request"
	"elegantGo/chapter17/controller/response"
	"elegantGo/chapter17/repository"
	"elegantGo/chapter17/repository/ent"
	"github.com/gin-gonic/gin"
)

type User struct {
	repo *repository.User
}

func NewUser(repo *repository.User) *User {
	ctr := new(User)
	ctr.repo = repo
	return ctr
}

func (ctr *User) One(c *gin.Context) (response.Data, error) {
	req := new(request.UserOne)
	if err := c.ShouldBind(req); err != nil {
		return nil, err
	}

	ooUser := ctr.repo.Fetch(c.Request.Context(), req.ID)
	if ooUser == nil {
		return nil, nil
	}

	return ooUser.Mapper(), nil
}

func (ctr *User) Many(c *gin.Context) (response.Data, error) {
	ooUsers := ctr.repo.FetchMany(c.Request.Context(), func(opt *ent.UserQuery) {
		opt.Limit(10)
	})
	return ooUsers.Mapper(), nil
}
